package com.yc.cloud.business;

import cn.hutool.json.JSONUtil;
import com.yc.cloud.common.model.response.Outcome;
import com.yc.cloud.socket.server.WebSocketServer;
import com.yc.cloud.socket.service.SocketServer;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.websocket.Session;

/**
 * @author 杨智杰
 * @since 2021/9/23 16:52
 */
@Service
public class DemoSocket implements SocketServer {

    {
        WebSocketServer.socketServer = this;
    }


    @Override
    public void onOpen(Session session) {
        System.out.println("新建链接:" + session.getId());
        sendMessage(session, "你好呀");
    }

    @Override
    public void onMessage(Session session, Object params) {
        System.out.println("收到消息:" + params);
        sendMessage(session, Outcome.success("欢迎使用yc-cloud的socket组件").setData("本消息为自动回复"));
    }

    @Override
    public void onError(Session session, Throwable error) {
        System.out.println("发生异常:" + error);
    }

    @Override
    public void onClose(Session session) {
        System.out.println("关闭链接:" + session.getId());
    }

    @Override
    @SneakyThrows
    public void sendMessage(Session session, Object data) {
        System.out.println("发出消息:" + JSONUtil.toJsonStr(data));
        session.getBasicRemote().sendText(JSONUtil.toJsonStr(data));
    }

}
